<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Mobile_Scenery_module extends CI_Module
{
    public $data;
    public $sid ;
    public function __construct(){
        parent::__construct();
        $this->sid = $GLOBALS['sid'];
        $this->data =$GLOBALS['config'];
        $this->load->model('ticket.ticket_model');
        $this->load->model('scenic.scenic_model');
        $this->load->model('member.User_model');
    }

    public function index()
    {

        $_GET['p'] = $province =intval( $_GET['p']);
        $_GET['c'] = $city = intval($_GET['c']);


        $keyword = $where = '';
        if(!empty($_GET['keyword'])){
            $keyword = addslashes($_GET['keyword']);
            $where = " (scenic_name LIKE '%$keyword%' OR a.city_name LIKE '%$keyword%' OR  b.description  LIKE '%$keyword%' ) ";
        }
        
        if($city){
            $where .= ($where ? ' AND ' : '' )." b.city=$city ";
        }

        if($province){
            $where .= ($where ? ' AND ' : '' ) . " b.province=$province ";
        }

        $pagesize = 8;
        $page = !empty($_GET['page']) && $_GET['page']>0 ? intval($_GET['page']) : 1;

        $this->data['datalist'] = $this->ticket_model->ticket_scenic_list($pagesize, $page, $where);
        foreach ($this->data['datalist'] as $k => $v)
        {
            $this->data['datalist'][$k]['file_url']  = empty($v['file_url'])?URLPRE.'static/public/images/nophoto.jpg':filter_img($v['file_url']);
            $this->data['datalist'][$k]['link']      = site_url('mobile/scenery/profile/?id=' . $v['scenic_id']);
        }
        foreach ($this->data['datalist'] as $k => $item) {
            $this->data['datalist'][$k]['price'] = $this->ticket_model->get_min_price_by_scenic_id($item['scenic_id']);
            $this->data['datalist'][$k]['description'] = mb_substr($item['description'], 0, 20);
        }
        $this->data['keyword'] = $keyword;
        $this->data['page'] = $page;
        $city = $this->data['sitecityname'];
        $this->data['common'] = array(
            array(
                'head'   => '景区门票' . ($keyword ? '-'.$keyword : $keyword),
                'title'   => $city.'旅游_景点大全_攻略_门票价格_'.$city.'旅游网',
                'keywords'   => $city.'景点,'.SITECITYNAME.'景点门票预订',
                'description'   => $city.'旅游景点，'.$city.'旅游网为您提供'.$city.'旅游景点介绍、图片、游客点评、热门景点推荐。'
            )
        );
        if(!empty($_GET['isajax'])){
            header('Content-type:application/json;charset=utf-8');
            echo json_encode($this->data['datalist']);
            exit;
        }else{
            $this->load->view(MOBILE_TEMPLATE_NAME.'/'.'scenery', $this->data);
        }

    }

    public function profile()
    {
        $id = intval($_GET['id']);
        $ticket = $this->ticket_model->ticket_list(100, 1, "a.scenic=$id");
        $group_pay_ticket = array();
        foreach ($ticket as $k => $t)
        {
            $group_pay_ticket[$t['payment_method_name']][] = $t;
        }
        $group_ticket = array();
        foreach ($group_pay_ticket as $k => $v)
        {
            foreach ($v as $ti)
            {
                $group_ticket[$k][$ti['category_name']][] = $ti;
            }
        }
        $this->data['site_phone'] = $GLOBALS['config']['site_service_phone'];
        $this->data['ticket']          = $ticket;
        $this->data['price']           = $this->ticket_model->get_min_price_by_scenic_id($id);
        $this->data['scenic']          = $this->scenic_model->scenic_by_id($id);
        $this->data['scenic']['photo'] = $this->scenic_model->photo_list(5, 1, 'scid='.$id);
        $this->data['group_ticket']    = $group_ticket;
        $content = strip_tags($this->data['scenic']['content'], '<img><a><p>');
        $patterns = array('/style=".*?"/i','/height=".*?"/i','/width=".*?"/i');
        $replacements = array(" "," "," ");
        $this->data['scenic']['content'] = preg_replace($patterns,$replacements, $content);
        $scenic_name = $this->data['scenic'] ['name'] ;
        $city = SITECITYNAME ;
        $this->data['common'] = array(
            array(
                'head'   => $scenic_name,
                'title'   => $scenic_name.'_介绍_攻略_门票价格_'.$city.'旅游网',
                'keywords'   => $scenic_name.'介绍,'.$scenic_name.'门票价格',
                'description'   => $scenic_name.'旅游指南，'.$city.'旅游网为您提供'.$scenic_name.'介绍、图片、费用、注意事项、旅游线路等信息。'.$city.'旅游网'
            )
        );
        $this->load->view(MOBILE_TEMPLATE_NAME.'/'.'scenery_profile', $this->data);
    }

    public function order()
    {
        $check_login = FALSE;
        @$user_id = $this->session->userdata('user_id');
        @$admin_user_id = $this->session->userdata('admin_user_id');

        if($user_id) $check_login = TRUE;
        if(!$check_login) redirect(site_url('mobile/member/login?referer='.$_GET['referer']));


        $ticket_id  = intval($_REQUEST['ticket_id']);
        $scenery_id = intval($_REQUEST['scenery_id']);
        $ticket = $this->ticket_model->ticket_list(1,1, "a.id=$ticket_id");
        $ticket = $ticket[0];

      /*  if(!empty($user_id)) $cat_type = 2 ;
        if(!empty($admin_user_id)) $cat_type = 1 ;*/
        if(strtolower($_SERVER['REQUEST_METHOD']) == 'post')
        {
            if($admin_user_id)  {
                return json_encode(array('status'=>'0','info' => '微名片身份不可以购买,请使用普通账户登陆'));
            }
            @$ticket_id = intval($_POST['ticket_id']);
            @$scenic_id = intval($_POST['scenic_id']);
            @$date = $_POST['date'];
            @$num  = intval($_POST['num']);
            @$contact_name = trim($_POST['name']);
            @$contact_phone = trim($_POST['phone']);
            if(empty($ticket_id) || empty($scenic_id) || empty($date) || $num<1 || !$check_login || empty($contact_name) || empty($contact_phone)
              ){
               return json_encode(array('status'=>'0','info' => '数据异常，订单生成失败!','msg' => 'order_fail'));
            }
            $price_info = $this->ticket_model->get_price_by_tid_date($ticket_id, $date);
            if(empty($price_info)){
                return json_encode(array('status'=>'0','info' => '订单生成失败!','msg' => 'order_fail'));
            }

            if($ticket['earlier_date'] || $ticket['earlier_time']){
                $if = date('Y-m-d', strtotime("-$ticket[earlier_time] day"));
                $end = strtotime($if .' '. $ticket['earlier_time']);

                if($end && $end> strtotime($price_info['date'])){
                    return json_encode(array('status'=>'0','info' => '无法购买该日门票!','msg' => 'order_fail'));
                }
            }

            $this->load->model('order.Orderinfo_model');
            $this->load->model('order.Ordercontacts_model');
            $this->load->model('order.Orderticket_model');
            //订单信息
            $order_data = array(
                'order_sn'      => $this->Orderinfo_model->set_order_sn(),
                'order_type'    => 2,//门票订单
                'cat_type'      => 6,//手机订单
                'order_account' => $price_info['price']*$num,
                'order_status'  => 2, //门票无需审核
                'pay_status'    => 1,//未支付
                'add_time'      => date('Y-m-d H:i:s',time()),
                'user_id'       => $user_id,//用户ID
                'admin_user_id' => intval(get_cookie('from_card')) ,//管理员ID
            );
            $order_id = $order_return_status = $this->Orderinfo_model->add_row($order_data);

            if($order_id){
                //联系人信息
                $contact_data = array(
                    'order_id'  => $order_id,
                    'name'      => $contact_name,
                    'email'     => '',
                    'phone_num' => $contact_phone,
                );
                $contact_return_status = $this->Ordercontacts_model->add_row($contact_data);

                //订单门票信息
                $batch_goods = array();
                $row = array(
                    'order_id'  => $order_id,
                    'ticket_id' => $ticket_id,
                    'scenic_id' => $scenic_id,
                    'price_id'  => $price_info['id'],
                    'price'     => $price_info['price'],
                    'user_date' => $price_info['date'],
                    'num'       => $num,
                );
                $batch_goods[] = $row;
                $batch_return_status = $this->Orderticket_model->add_batch($batch_goods);

                if($contact_return_status&&$batch_return_status){

                    //发送短信
                    $ticket_order_template = $GLOBALS['config']['ticket_order_template_submit'];

                    //短信内容
                    $content = str_replace(array('{$order_sn}','{$scenic_name}','{$ticket_name}','{$user_date}','{$num}','{$contact_name}','{$contact_phone}','{$order_account}'),array($order_data['order_sn'],
                        $ticket['scenic_name'],$ticket['name'],$price_info['date'],$num,$contact_data['name'],$contact_data['phone_num'],$order_data['order_account']),$ticket_order_template);

                    $this->User_model->_send_sms($contact_data['phone_num'],$content);
                    $this->User_model->_send_more_sms($GLOBALS['config']['notify_num'], $content);


                    return json_encode(array('status'=>'1','info' => '提交订单成功!','msg' => 'order_fail'));

                }else{
                    return json_encode(array('status'=>'0','info' => '订单生成失败!','msg' => 'order_fail'));
                }
            }else{
                return json_encode(array('status'=>'0','info' => '订单生成失败!','msg' => 'order_fail'));
            }
        }

        $ticket['price_list'] = $this->ticket_model->get_price($ticket['id'],0,TRUE, FALSE);
        $this->data['ticket'] = $ticket;
        $this->data['scenic'] = $this->scenic_model->scenic_by_id($scenery_id);
        $this->data['form_url'] = site_url('mobile/scenery/order');
        $this->data['common'] = array(
            array(
                'head'   => '填写门票订单',
                'title'   => '填写门票订单'
            )
        );
        $this->load->view(MOBILE_TEMPLATE_NAME.'/'.'scenery_order', $this->data);
    }



    public function ticketcity(){

        $data = array();
        $site = $GLOBALS['config'];

        $province = $_GET['p'];
        $city = $_GET['c'];

        if(!$city && !$province) {
            $province = $site['siteprovince'] ? $site['siteprovince'] : 1600;
            $city = $site['sitecity'];
        }
        $areas = $this->area_model->get_area_name(array($city , $province), false);

        $data['province'] = $province;
        $data['city_name'] = $areas[$city ? $city : $province];
        $data['city'] = $city;

        //默认城市列表
        $area_list = $this->area_model->get_area_by_id($site['siteprovince'], 'code_level ASC, poi_code ASC');
        $data['area_list'] = $this->ticket_model->check_scenery_by_city($area_list);


        $this->data = array_merge($this->data, $data);
        $this->data['common'] = array(
            array(
                'noback' => false,
                'head'   => '选择城市',
                'title'   => '选择城市',
            )
        );
        $this->load->view(MOBILE_TEMPLATE_NAME.'/ticketcity', $this->data);
    }

}